package auction

import auth.User

class Bid {
	
	/*
	Die Attribute werden definiert.
	*/
	BigDecimal bidAmount
	Date dateCreated //automatically filled by grails on creation
	
	/*
	Die Relationen zu Auktion und User werden definiert.
	Ein Gebot geh�rt zu einem User.		(1:1)
	Ein Gebot geh�rt zu einer Auktion. 	(1:1)
	 */
	static belongsTo = [user:User, auction:Auction]
	
	
	/*
	Hier werden die Beschr�nkungen der Domain-Attribute definiert.
	 */
    static constraints = {
		bidAmount(
			min:1.0, 
			scale:2, 
			blank:false,				
			validator: minAmount
			)
		dateCreated(validator:inTime)
		user(validator:biddingUser)
		// auction + amount should be unique together - no such constraint available :(
		// dateCreated must be smaller than endDate of auction
    }
	
	
	/* -------- VALIDATORS -------------- */
	
	/**
	 * bidAmount (stored in val) must be bigger than amount 
	 * of previous bid for this auction
	 */
	static minAmount = {val,obj ->
		def auctionInstance = obj.properties['auction']
		return val >= auctionInstance.minBidAmount //FIXME: not possible due to inconsistent state of previous bid (or self)?
	 }
	
	/**
	 * Current date must be smaller or identical to endDate 
	 * of auction.
	 * Finally found a solution, thanks to http://stackoverflow.com/questions/7798442/grails-date-date-range-constraint
	 */
	static inTime = {val,obj ->
		def auctionInstance = obj.properties['auction']
		return new Date() <= auctionInstance.endDate
	}
	
	/**
	 * Bidding user must not be the creator of the auction
	 */
	static biddingUser = {val,obj ->
		def auctionInstance = obj.properties['auction']
		return val != auctionInstance.user
	}
	
	/* ----------- EVENT LISTENERS --------- */
	
	/**
	* nach dem anlegen des Gebots sollte der Überbotene benachrichtigt werden
	*/
	def EmailService
	//Hibernate-Voodoo-Zauber: Aus irgendeinem Grund funktioniert afterInsert nicht.
	def beforeInsert() {
	   EmailService.notifyOverbidden(this)
   }
	
	

	
}
